package ua.com.abakumov.android.prostopleer.engines.u

import ua.com.abakumov.android.prostopleer.util.Composition

import java.util.regex.{Matcher, Pattern}
import java.util
import org.jsoup.Jsoup
import scala.List

import java.util.{List => JList}


/**
 *
 * User: aabakumov, Date: 24.12.12, Time: 14:24 
 */
class ProstoPleerSearcher extends Searcher {

  type Compositions = JList[Composition]

  override def search(request: String): List[Composition] = {
    val reply : Option[String] = new GetData().data(request, "http", "prostopleer.com", "80", "/search", "q=")

    reply match {
      case Some(s) => parse(s)
      case None => List[Composition]()
    }
  }



  private def parse(rawResult: String): List[Composition] = {
    /**
     * Extract tracks html to help html parser (make it faster)
     *
     * @param html raw html
     * @return clean html
     */
    def extractTracks(html: String): String = {
      val pattern: Pattern = Pattern.compile("<li duration(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>")
      val matcher: Matcher = pattern.matcher(html)
      val sb: StringBuilder = new StringBuilder
      while (matcher.find) {
        val group: String = matcher.group
        sb.append(group)
      }
      sb.toString()
    }

    val compositions = List[Composition]()

    val html = extractTracks(rawResult)
    val doc = Jsoup.parse(html)
    val lis = doc.select("li")

    import scala.collection.JavaConversions._
    for (row <- lis) {
      val link: String = row.attr("link")
      val singer: String = row.attr("singer")
      val song: String = row.attr("song")
      val size: String = row.attr("size")

      Composition(link, singer, song, size) :: compositions
    }

    compositions
  }
}
